//
//  DigitalTransferViewController.m
//  HYApp
//
//  Created by Jianbo Cai on 2020/8/12.
//  Copyright © 2020 Unidax. All rights reserved.
//

#import "DigitalTransferViewController.h"
#import "SheetView.h"
#import "DigitalTransferRequestViewController.h"
#import "HYNetHelper.h"
#import "TransferTenorEntity.h"

@interface DigitalTransferViewController ()

@property (weak, nonatomic) IBOutlet UILabel *transferTitle;
@property (weak, nonatomic) IBOutlet UITextField *accountTextField;
@property (weak, nonatomic) IBOutlet UITextField *amountTextField;
@property (weak, nonatomic) IBOutlet UITextField *tenorTextField;
@property (weak, nonatomic) IBOutlet UILabel *amountTitle;
@property (weak, nonatomic) IBOutlet UILabel *availableValue;
@property (weak, nonatomic) IBOutlet UILabel *feeLabel;
@property (weak, nonatomic) IBOutlet UIButton *confirmButton;

@property (nonatomic, strong) NSArray<TransferTenorEntity *> *tenorArray;
@property (nonatomic, strong) TransferTenorEntity *selectTenor;

@property (nonatomic, strong) NSMutableArray<ETHEntity *> *toETHList;
@property (nonatomic, strong) NSMutableArray<NSString *> *toETHTitles;
@property (nonatomic, strong) ETHEntity *toETH;

@property (nonatomic, assign) BOOL isDigital;
@property (nonatomic, strong) ETHEntity *fromETH;

@property (weak, nonatomic) IBOutlet UILabel *toAccount;
@property (weak, nonatomic) IBOutlet UILabel *tenorTitle;
@property (weak, nonatomic) IBOutlet UILabel *availableTitle;
@property (weak, nonatomic) IBOutlet UILabel *label1;

@end

@implementation DigitalTransferViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.toAccount.text = JFMainLocalizedString(@"withdraw.to-account");
    self.availableTitle.text = [NSString stringWithFormat:@"%@：", JFMainLocalizedString(@"myAssets.available")];
    self.label1.text = JFMainLocalizedString(@"transfer.fee");
    self.amountTextField.placeholder = [NSString stringWithFormat:@"%@", JFMainLocalizedString(@"deal.amount")];
    [self.confirmButton setTitle:JFMainLocalizedString(@"confirm") forState:UIControlStateNormal];
    
    [self.confirmButton setBackgroundImage:[UIImage imageWithColor:UIColorFromHex(0xCCCCCC) size:self.confirmButton.frame.size] forState:UIControlStateDisabled];
    [self.confirmButton setBackgroundImage:[UIImage imageWithColor:UIColorFromHex(0x70896A) size:self.confirmButton.frame.size] forState:UIControlStateNormal];
    self.confirmButton.enabled = NO;
    
    self.toETHList = [NSMutableArray arrayWithCapacity:3];
    for (ETHEntity *eth in self.walletsEntity.eth) {
        for (BalanceListEntity *balance in eth.balance) {
            if (balance == self.fromBalance) {
                self.fromETH = eth;
                self.isDigital = [eth.metadata.type isEqualToString:@"Digital"];
            }else {
                if ([balance.asset_symbol isEqualToString:self.fromBalance.asset_symbol]) {
                    [self.toETHList addObject:eth];
                }
            }
        }
    }
    self.toETH = self.toETHList.firstObject;
    
    NSString *string = [NSString stringWithFormat:@"%@ %@ %@ %@.", JFMainLocalizedString(@"transactions.transfer"), self.fromBalance.asset_symbol, JFMainLocalizedString(@"transactions.From"), [self getAccountName:self.fromETH]];
    NSMutableAttributedString *attStr = [[NSMutableAttributedString alloc]initWithString:string];
    [attStr addAttributes:@{NSForegroundColorAttributeName: UIColorFromHex(0xF8A828)} range:[string rangeOfString:self.fromBalance.asset_symbol]];
    [attStr addAttributes:@{NSForegroundColorAttributeName: UIColorFromHex(0xF8A828)} range:[string rangeOfString:[self getAccountName:self.fromETH]]];
    self.transferTitle.attributedText = attStr;
    
    
    [self requestData];
}

- (void)requestData {
    NSString *amount = self.amountTextField.text.length ? self.amountTextField.text : @"0";
    
    WEAKSELF
    [HYNetHelper tenor:self.fromBalance.asset_symbol from_wallet_id:self.fromETH.wallet_id to_wallet_id:self.toETH.wallet_id amount:amount callBack:^(JFResultVo *resultVo) {
        if (!resultVo.errorNo) {
            weakSelf.tenorArray = [NSArray yy_modelArrayWithClass:[TransferTenorEntity class] json:resultVo.results[@"data"]];
            weakSelf.selectTenor = weakSelf.tenorArray.firstObject;
        }
    }];
}

- (void)setToETH:(ETHEntity *)toETH {
    _toETH = toETH;
    
    self.accountTextField.text = [self getAccountName:toETH];
    self.availableValue.text = [NSString stringWithFormat:@"%@ %@", self.fromBalance.available_balance_display, self.fromBalance.asset_symbol];
    
    self.title = [NSString stringWithFormat:@"%@ %@", JFMainLocalizedString(@"transactions.transfer"), self.fromBalance.asset_symbol];
    
    NSString *unit = [self.fromBalance.asset_symbol isEqualToString:@"HKD"] ? @"HKD" : @"USD";
    self.amountTitle.text = [NSString stringWithFormat:@"%@（%@)", JFMainLocalizedString(@"deal.amount"), unit];
    self.feeLabel.text =  [NSString stringWithFormat:@"-- %@", unit];
}

- (void)setSelectTenor:(TransferTenorEntity *)selectTenor {
    _selectTenor = selectTenor;
    
    NSString *string = [NSString stringWithFormat:@"%@: %@", selectTenor.des, selectTenor.fee_description];
    self.tenorTextField.text = string;
    self.feeLabel.text =  [NSString stringWithFormat:@"%@ %@", selectTenor.fee, self.fromBalance.asset_symbol];
}

- (IBAction)editChangeAction:(id)sender {
    if ((self.accountTextField.text.length > 0) && (self.amountTextField.text.length > 0) && (self.tenorTextField.text.length > 0)) {
        self.confirmButton.enabled = YES;
    }else {
        self.confirmButton.enabled = NO;
    }
    [self requestData];
}

- (IBAction)selectAccountAction:(id)sender {
    SheetView *view = [[[NSBundle mainBundle] loadNibNamed:@"SheetView" owner:nil options:nil] firstObject];
    view.frame = self.navigationController.view.bounds;
    view.titleArray = self.toETHTitles;
    WEAKSELF
    view.selectAction = ^(NSInteger index) {
        weakSelf.toETH = weakSelf.toETHList[index];
    };
    [self.navigationController.view addSubview:view];
}

- (IBAction)selectTenorAction:(id)sender {
    NSMutableArray *array = [NSMutableArray arrayWithCapacity:2];
    for (TransferTenorEntity *tenor in self.tenorArray) {
        NSString *string = [NSString stringWithFormat:@"%@: %@", tenor.des, tenor.fee_description];
        [array addObject:string];
    }
    SheetView *view = [[[NSBundle mainBundle] loadNibNamed:@"SheetView" owner:nil options:nil] firstObject];
    view.frame = self.navigationController.view.bounds;
    view.titleArray = array;
    WEAKSELF
    view.selectAction = ^(NSInteger index) {
        weakSelf.selectTenor = weakSelf.tenorArray[index];
    };
    [self.navigationController.view addSubview:view];
}

- (IBAction)confirmAction:(id)sender {
    DigitalTransferRequestEntity *entity = [[DigitalTransferRequestEntity alloc]init];
    entity.fromAccount = [self getAccountName:self.fromETH];
    entity.toAccount = self.accountTextField.text;
    entity.amount = self.amountTextField.text;
    entity.tenor = self.selectTenor;
    entity.to_wallet_id = self.toETH.wallet_id;
    entity.asset_symbol = self.fromBalance.asset_symbol;
    entity.wallet_id = self.fromETH.wallet_id;
    
    DigitalTransferRequestViewController *vc = [[UIStoryboard storyboardWithName:@"Main" bundle:nil]instantiateViewControllerWithIdentifier:@"DigitalTransferRequestViewController"];
    vc.entity = entity;
    [self.navigationController pushViewController:vc animated:YES];
}


- (NSMutableArray<NSString *> *)toETHTitles {
    if (!_toETHTitles) {
        _toETHTitles = [NSMutableArray arrayWithCapacity:self.toETHList.count];
        for (ETHEntity *eth in self.toETHList) {
            [_toETHTitles addObject:[self getAccountName:eth]];
        }
    }
    return _toETHTitles;
}

- (NSString *)getAccountName:(ETHEntity *)eth {
    if ([eth.metadata.type isEqualToString:@"digital"]) {
        return JFMainLocalizedString(@"digitalAccount");
    }else {
        NSString *string = [NSString stringWithFormat:@"%@Account", eth.metadata.jurisdiction];
        return JFMainLocalizedString(string);
    }
}

@end
